package com.example.demo03_mvm.viewmodel;

import android.app.Application;

import androidx.annotation.NonNull;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.Observer;

import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.ToastUtils;
import com.example.demo03_mvm.App;
import com.example.demo03_mvm.model.UserEntity;
import com.example.demo03_mvm.repos.UserRepso;
import com.example.demo03_mvm.utils.ACache;
import com.google.gson.Gson;

import java.util.HashMap;

import okhttp3.MediaType;
import okhttp3.RequestBody;

public class UserViewModel extends BaseViewModel{
    UserRepso userRepso;
    public UserViewModel(@NonNull Application application) {
        super(application);
        userRepso=new UserRepso();
    }

    public void register(HashMap<String, String> map, LifecycleOwner owner){
        String json = new Gson().toJson(map);
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), json);

        userRepso.register(body).observe(owner, new Observer<UserEntity>() {
            @Override
            public void onChanged(UserEntity userEntity) {
                if(userEntity.getCode()==200){//成功
                    ARouter.getInstance().build("/app/LoginActivity").navigation();
                }else{
                    ToastUtils.showLong(userEntity.getMessage());
                }
            }
        });
    }
    public void login(HashMap<String, String> map, LifecycleOwner owner){
        String json = new Gson().toJson(map);
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), json);

        userRepso.login(body).observe(owner, new Observer<UserEntity>() {
            @Override
            public void onChanged(UserEntity userEntity) {
                if(userEntity.getCode()==200){//成功
                    ACache.get(App.getContext()).put("token",userEntity.getData().getToken());
                    ARouter.getInstance().build("/app/DetailActivity").navigation();
                }else{
                    ToastUtils.showLong(userEntity.getMessage());
                }
            }
        });
    }
}
